package com.bp.scoringgun.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

@Component
public class GitHubArchiveDownloader {
    @Value("${scoring-gun.url}")
    private String BASE_URL ;
    @Value("${scoring-gun.path}")
    private String directoryPath ;

    public void downloadAndDecompress(String date,int hour) {
        String hourStr = String.format("%d", hour);
        String fileName = String.format("%s-%s.json.gz", date, hourStr);
        String fileURL = BASE_URL + fileName;

        try {
            System.out.println("Downloading: " + fileName);
            downloadFile(fileURL,directoryPath, fileName);
            System.out.println("Downloaded: " + fileName);

            String uncompressedFileName = fileName.replace(".gz", "");
            decompressGzipFile(directoryPath+"\\"+fileName, directoryPath+"\\"+uncompressedFileName);
            System.out.println("Decompressed: " + uncompressedFileName);
        } catch (IOException e) {
            System.err.println("Error processing " + fileName + ": " + e.getMessage());
        }

    }

    private void downloadFile(String fileURL, String directoryPath, String fileName) throws IOException {
        HttpURLConnection httpConn = (HttpURLConnection) new URL(fileURL).openConnection();
        httpConn.setRequestMethod("GET");
        httpConn.setConnectTimeout(5000);
        httpConn.setReadTimeout(5000);

        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 创建指定目录路径的文件
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                directory.mkdirs();  // 创建目录
            }

            // 将下载的文件保存到指定目录下
            try (InputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
                 FileOutputStream outputStream = new FileOutputStream(new File(directory, fileName))) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        } else {
            throw new IOException("Server returned non-OK status: " + httpConn.getResponseCode());
        }
        httpConn.disconnect();
    }

    private void decompressGzipFile(String compressedFile, String decompressedFile) throws IOException {
        try (GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(compressedFile));
             FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = gzipInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
        }
        // 删除原压缩文件
        File originalFile = new File(compressedFile);
        if (originalFile.exists()) {
            if (!originalFile.delete()) {
                System.err.println("Failed to delete the original compressed file: " + compressedFile);
            }
        }

    }
}
